<script setup>
import 'leaflet/dist/leaflet.css'
import '@supermap/iclient-leaflet/css/index'

import iServerConfigUrl from '/iServerConfig.json?url'

import { Edit, Download } from '@element-plus/icons-vue'
import { ElLoading, ElMessage } from 'element-plus'
import $ from 'jquery'
import axios from 'axios'

import L from 'leaflet'
import '@supermap/iclient-leaflet'
import 'proj4leaflet'

import { inject } from 'vue'

const optionsProps = {
    value: 'value',
    label: 'label'
}

const templatesOptions = [
    {
        value: 'A2_landscape',
        label: 'A2_landscape'
    },
    {
        value: 'A3_portrait',
        label: 'A3_portrait'
    },
    {
        value: 'A4_landscape',
        label: 'A4_landscape'
    },
    {
        value: 'A2_portrait',
        label: 'A2_portrait'
    },
    {
        value: 'A3_landscape',
        label: 'A3_landscape'
    },
    {
        value: 'CustomLayout',
        label: 'CustomLayout'
    }
]
</script>

<template>
    <el-button :icon="Edit" circle class="webPrintingEditBtn" @click="webPrintingEditCardStatus" />
    <el-card class="WebPrintingCard">
        <template #header>
            <div class="WebPrintingCardHeader">
                <span>Web 打印</span>
            </div>
        </template>
        <span class="layoutTitle">布局模板</span>
        <el-select-v2 class="templatesSelect" v-model="templateName" filterable :props="optionsProps" :options="templatesOptions" placeholder="请选择需要打印的布局模板"
            placement="bottom"></el-select-v2>
        <span class="dpiTitle">DPI</span>
        <el-input-number class="dpiInputNumber" v-model="exportDPI" :step="1" :min="1" :max="400" />
        <span class="titleTitle">主标题：</span>
        <el-input class="titleInput" v-model="title" placeholder="请输入布局主标题" />
        <span class="subTitleTitle">副标题：</span>
        <el-input class="subTitleInput" v-model="subTitle" placeholder="请输入布局副标题" />
        <span class="authorTitle">作者：</span>
        <el-input class="authorInput" v-model="author" placeholder="请输入作者" />
        <span class="copyrightTitle">版权信息：</span>
        <el-input class="copyrightInput" v-model="copyright" placeholder="请输入版权信息" />
        <el-button class="button" :icon="Download" round @click="handleWebPrintingBtnClicked">打印</el-button>
        <el-link class="downloadUrl" :href="downloadUrl" type="primary" :disabled=downloadUrlDisabled>Web 打印结果下载地址</el-link>
    </el-card>
</template>

<script>
export default {
    name: 'WebPrint',
    data() {
        return {
            restMapUrl: undefined,
            restMapLayer: undefined,
            webPrinting: undefined,
            downloadUrl: '',
            templateName: 'A2_landscape',
            webPrintingLevel: 4,
            mapCenter: {
                x: 104.06,
                y: 30.67
            },
            littleMapCenter: {
                x: 104.06,
                y: 30.67
            },
            littleMapScale: 0.000000005608,
            exportDPI: 96,
            downloadUrlDisabled: true,
            map: undefined,
            mapScales: [
                3.3803271432053097e-9,
                6.760654286410619e-9,
                1.3521308572821239e-8,
                2.7042617145642478e-8,
                5.4085234291284955e-8,
                1.0817046858256991e-7,
                2.1634093716513982e-7,
                4.3268187433027964e-7,
                8.653637486605593e-7,
                0.0000017307274973211186,
                0.000003461454994642237,
                0.000006922909989284474,
                0.000013845819978568949,
                0.000027691639957137897,
                0.000055383279914275794,
                0.00011076655982855159,
                0.00022153311965710318,
                0.00044306623931420635
            ],
            title: '主标题',
            subTitle: '副标题',
            author: '作者',
            copyright: '版权信息'
        }
    },
    mounted() {
        this.map = inject('map');

        axios.get(iServerConfigUrl).then(res => {
            var iServerConfig = res.data;
            this.restMapUrl = `${iServerConfig.urls.WebPrint.protocol}://${iServerConfig.urls.WebPrint.hostname}:${iServerConfig.urls.WebPrint.port}/${iServerConfig.urls.WebPrint.restMapUrl}`;
            this.webPrinting = `${iServerConfig.urls.WebPrint.protocol}://${iServerConfig.urls.WebPrint.hostname}:${iServerConfig.urls.WebPrint.port}/${iServerConfig.urls.WebPrint.webPrinting}`;

            // 还原 map 显示范围
            if (this.map._size.x !== document.body.clientWidth) {
                $("#map")[0].style.width = '';
                this.map._size.x = document.body.clientWidth;
            }

            this.map.options.crs = L.CRS.EPSG4326;;
            this.map.flyTo([35.12, 108.48], 4);

            // 添加底图
            this.restMapLayer = new L.supermap.tiledMapLayer(this.restMapUrl).addTo(this.map);
        }).catch(err => {
            ElMessage.error(err.stack);
        });
    },
    methods: {
        // 更新 web打印参数面板状态
        webPrintingEditCardStatus() {
            var webPrintingStyleCard = $(".WebPrintingCard")[0];
            if (webPrintingStyleCard.style.display !== 'none') {
                webPrintingStyleCard.style.display = 'none';
            } else {
                webPrintingStyleCard.style.display = 'block';
            }
        },

        // Web 打印
        handleWebPrintingBtnClicked() {
            // Loading
            var loading = ElLoading.service({
                lock: true,
                text: 'Web 打印中',
                background: 'rgba(0, 0, 0, 0.6)',
            });

            try {
                var currentCenter = this.map.getCenter();
                this.mapCenter.x = currentCenter.lng;
                this.mapCenter.y = currentCenter.lat;
                this.littleMapCenter.x = currentCenter.lng;
                this.littleMapCenter.y = currentCenter.lat;
                this.webPrintingLevel = this.map._zoom;
                this.littleMapScale = this.mapScales[this.webPrintingLevel - 1];

                var webPrintingContent = `{"content":{"type":"WEBMAP","value":{"extent":{"leftBottom":{"x":103.9,"y":30.53},"rightTop":{"x":104.23,"y":30.81}},"maxScale":"1:2256.9988666882755","level":${this.webPrintingLevel},"center":{"x":${this.mapCenter.x},"y":${this.mapCenter.y}},"layers":[{"layerType":"TILE","name":"China4326","url":"${this.$store.state.iserver.protocol}://${this.$store.state.iserver.hostname}:${this.$store.state.iserver.port}/iserver/services/map-China4326/rest/maps/China4326"}],"description":"","projection":"EPSG:4326","minScale":"1:295829355.45456564","title":"China4326","version":"2.0.0"}},"layoutOptions":{"templateName":"${this.templateName}","title":"${this.title}","subTitle":"${this.subTitle}","author":"${this.author}","copyright":"${this.copyright}","northArrowOptions":{"picAsUrl":"file://NorthArrow.svg"},"scaleBarOptions":{"scaleText":"比例尺"},"legendOptions":{"title":"图例","customItems":[{"name":"省","picAsUrl":"${this.$store.state.iserver.protocol}://${this.$store.state.iserver.hostname}:${this.$store.state.iserver.port}/iserver/services/map-China4326/rest/maps/China4326/layers/Province4326@World4326@@China4326/legend"},{"name":"省名","picAsUrl":"${this.$store.state.iserver.protocol}://${this.$store.state.iserver.hostname}:${this.$store.state.iserver.port}/iserver/services/map-China4326/rest/maps/China4326/layers/Province4326@World4326.1@@China4326/legend"}]},"littleMapOptions":{"center":{"x":${this.littleMapCenter.x},"y":${this.littleMapCenter.y}},"scale":${this.littleMapScale},"layers":[{"layerType":"TILE","name":"China4326","url":"${this.$store.state.iserver.protocol}://${this.$store.state.iserver.hostname}:${this.$store.state.iserver.port}/iserver/services/map-China4326/rest/maps/China4326"}]}},"exportOptions":{"format":"pdf","dpi":${this.exportDPI}}}`;

                // iDesktopX 自定义 UGO 布局模板参数构建
                if (this.templateName === 'CustomLayout') {
                    webPrintingContent = `{"content":{"type":"WEBMAP","value":{"extent":{"leftBottom":{"x":103.9,"y":30.53},"rightTop":{"x":104.23,"y":30.81}},"maxScale":"1:2256.9988666882755","level":${this.webPrintingLevel},"center":{"x":${this.mapCenter.x},"y":${this.mapCenter.y}},"layers":[{"layerType":"TILE","name":"China4326","url":"${this.$store.state.iserver.protocol}://${this.$store.state.iserver.hostname}:${this.$store.state.iserver.port}/iserver/services/map-China4326/rest/maps/China4326"}],"description":"","projection":"EPSG:4326","minScale":"1:295829355.45456564","title":"China4326","version":"2.0.0"}},"layoutOptions":{"templateName":"${this.templateName}","title":"${this.title}","subTitle":"${this.subTitle}","author":"${this.author}","copyright":"${this.copyright}"},"exportOptions":{"format":"pdf","dpi":${this.exportDPI}}}`;
                }

                axios({
                    method: 'POST',
                    url: this.webPrinting,
                    data: webPrintingContent
                }).then(res => {
                    var data = res.data;
                    for (let i = 0; i < data.length; i++) {
                        const path = data[i].path;
                        this.webPrintingDownloading(path, loading);
                    }
                }).catch(err => {
                    console.log(err);
                })
            }
            catch (err) {
                loading.close();
                ElMessage.error(err.stack);
            }
        },

        // Web 打印进度
        webPrintingDownloading(url, loading) {
            axios.get(url).then(res => {
                var status = res.data.status;
                if (status === 'ERROR') {
                    loading.close();
                    ElMessage.error('Web 打印失败！请检查打印参数并选择合适的布局模板');
                } else if (status === 'FINISHED') {
                    loading.close();
                    ElMessage.success('Web 打印成功，请下载打印结果');
                    this.downloadUrl = res.data.result.downloadUrl;
                    this.downloadUrlDisabled = false;
                } else {
                    setTimeout(() => {
                        this.webPrintingDownloading(url, loading);
                    }, 1000);
                }
            }).catch(err => {
                console.log(err);
                loading.close();
                ElMessage.error(`Web 打印失败！${err.stack}`);
            })
        }
    }
}
</script>

<style scoped>
.webPrintingEditBtn {
    top: 90px;
    right: 30px;
    z-index: 1000;
    position: absolute;
    background-color: rgba(240, 255, 255, 0.7);
}

.WebPrintingCard {
    position: absolute;
    width: 360px;
    height: 560px;
    z-index: 999;
    background-color: rgba(240, 255, 255, 0.7);
    right: 0px;
    margin: 20px;
    border-radius: 20px;
    line-height: 840px;
}

.WebPrintingCardHeader {
    line-height: 32px;
    font-weight: 600;
    font-size: 24px;
}

.layoutTitle {
    font-weight: 600;
    font-size: 18px;
    position: absolute;
    left: 26px;
    line-height: 32px;
}

.templatesSelect {
    position: absolute;
    top: 130px;
    left: 0px;
    padding: 0px 20px;
    width: calc(100% - 40px);
}

.dpiTitle {
    font-weight: 600;
    font-size: 18px;
    position: absolute;
    left: 26px;
    line-height: 32px;
    top: 180px;
}

.dpiInputNumber {
    font-size: 16px;
    position: absolute;
    left: 20px;
    line-height: 32px;
    top: 220px;
    width: calc(100% - 40px);
}

.titleTitle {
    font-weight: 600;
    font-size: 18px;
    position: absolute;
    left: 26px;
    line-height: 32px;
    top: 280px;
}

.titleInput {
    position: absolute;
    top: 280px;
    left: 130px;
    width: calc(100% - 150px);
}

.subTitleTitle {
    font-weight: 600;
    font-size: 18px;
    position: absolute;
    left: 26px;
    line-height: 32px;
    top: 330px;
}

.subTitleInput {
    position: absolute;
    top: 330px;
    left: 130px;
    width: calc(100% - 150px);
}

.authorTitle {
    font-weight: 600;
    font-size: 18px;
    position: absolute;
    left: 26px;
    line-height: 32px;
    top: 380px;
}

.authorInput {
    position: absolute;
    top: 380px;
    left: 130px;
    width: calc(100% - 150px);
}

.copyrightTitle {
    font-weight: 600;
    font-size: 18px;
    position: absolute;
    left: 26px;
    line-height: 32px;
    top: 430px;
}

.copyrightInput {
    position: absolute;
    top: 430px;
    left: 130px;
    width: calc(100% - 150px);
}

.downloadUrl {
    padding: 0px 20px;
    line-height: 32px;
}

.button {
    font-size: 16px;
    font-weight: 600;
}
</style>